package com.kye.express.business.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.aspsine.fragmentnavigator.FragmentNavigator;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jaeger.library.StatusBarUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.jpush.JpushNotificationUtils;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.business.main.fragmentAdapter.MainFragmentAdapter;
import com.kye.express.business.main.tab.MainTabEntity;
import com.kye.express.business.order.NameCertificationUtils;
import com.kye.express.business.order.add_order.AddOrderActivity;
import com.kye.express.business.order.scan_code_add_order.ScanCodeAddOrderActivity;
import com.kye.express.business.scanner.WaybillScannerActivity;
import com.kye.express.business.service.popup.MoreWindow;
import com.kye.express.databinding.ActivityMainBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.model.UserSession;
import com.kye.model.bean.order.OrderValidationNameCertificationBean;
import com.kye.model.bean.order.scan_code_order.ScanCodeOrderAddress;

import java.util.ArrayList;

import io.reactivex.functions.Consumer;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : 主界面
 * @update_reason : <UpdateReason>
 */
public class MainActivity extends BaseAppCompatActivity implements MainContract.MainView {

    private String TAG = MainActivity.class.getSimpleName();

    protected FragmentNavigator fragmentNavigator;
    protected MainFragmentAdapter mainFragmentAdapter;
    protected ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    protected ActivityMainBinding mainDataBinding;

    protected MainContract.MainPresenter mPresenter;

    private MoreWindow mMoreWindow;
    private Dialog mDialog;
    private Dialog mTipsDialog;
    private View.OnClickListener mOnClickAddOrderListener;

    private Dialog mProgressDialog;

    public static void startActivity(Context context) {
        context.startActivity(
                new Intent(context, MainActivity.class)
        );
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.purple_0), 0);
        mainDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initViews(savedInstanceState);
        initEvents();
        mPresenter = new MainContract.MainPresenter();
        mPresenter.bind(this);
//        presenter.checkUpdate(getApplication());
    }

    @Override
    protected void onResume() {
        super.onResume();
        JpushNotificationUtils.checkNeedHandleJpushMessage(this);
    }

    private void initViews(Bundle savedInstanceState) {
        mainFragmentAdapter = new MainFragmentAdapter();
        fragmentNavigator = new FragmentNavigator(getSupportFragmentManager(), mainFragmentAdapter, R.id.flContainer);
        fragmentNavigator.setDefaultPosition(MainFragmentAdapter.TAB_POSITION_HOME);
        if (fragmentNavigator != null) {
            fragmentNavigator.onCreate(savedInstanceState);
        }
        for (int i = 0; i < mainFragmentAdapter.getCount(); i++) {
            mTabEntities.add(new MainTabEntity(mainFragmentAdapter.getTABS()[i], mainFragmentAdapter.getmIconSelectIds()[i], mainFragmentAdapter.getmIconUnselectIds()[i]));
        }
        mainDataBinding.tabLayout.setTabData(mTabEntities);
        mainDataBinding.tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                setCurrentTabPosition(position);

                // 每次点击礼物Fragment都判断有没有登录
                if (position == MainFragmentAdapter.TAB_POSITION_GIFT) {
                    if (UserSession.getInstance().getUser() == null || !UserSession.getInstance().getUser().isLogin()) {
                        LoginActivity.startActivity(MainActivity.this);
                    }
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        setCurrentTabPosition(fragmentNavigator.getCurrentPosition());
        // todo : block the service item, ugly but useful at least now
        initServiceIconWidth();
    }

    private void initServiceIconWidth() {
        ViewGroup.LayoutParams layoutParams = mainDataBinding.flService.getLayoutParams();
        layoutParams.width = ScreenUtils.getScreenWidth() / 5;
        mainDataBinding.flService.setLayoutParams(layoutParams);
    }

    private void initEvents() {
        RxView.clicks(mainDataBinding.flService)
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showMoreWindow(mainDataBinding.flService);
                    }
                });

        mOnClickAddOrderListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NameCertificationUtils.checkStartActivity(MainActivity.this, mDialog, new NameCertificationUtils.CheckListener() {
                    @Override
                    public void onCreateDialog(Dialog dialog) {
                        mDialog = dialog;
                    }

                    @Override
                    public void startLoginActivity() {
                        LoginActivity.startActivity(MainActivity.this);
                    }

                    @Override
                    public void checkNameCertification(NameCertificationUtils.CheckListener.Type type) {
                        mPresenter.checkNameCertification(type);
                    }

                    @Override
                    public void checkCustomCodeForStartScanCodeAddOrder(String customCode) {
                        mPresenter.checkCustomCodeForStartScanCodeAddOrder(customCode);
                    }
                });
            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (fragmentNavigator != null) {
            fragmentNavigator.onSaveInstanceState(outState);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMoreWindow != null) mMoreWindow.destroy();
    }

    public void setCurrentTabPosition(int position) {
        invalidateOptionsMenu();

        fragmentNavigator.showFragment(position);
        mainDataBinding.tabLayout.setCurrentTab(position);
    }

    private void showMoreWindow(View view) {
        if (null == mMoreWindow) {
            mMoreWindow = new MoreWindow(this);
            mMoreWindow.setOnClickAddOrderListener(mOnClickAddOrderListener);
            mMoreWindow.init();
        }

        mMoreWindow.showMoreWindow(view);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {
        mProgressDialog = KyeProgressDialog.show(this, mProgressDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mProgressDialog);
    }

    @Override
    public void onNeedValidation(OrderValidationNameCertificationBean bean, NameCertificationUtils.CheckListener.Type type) {
        if (bean.isValidation()) {
            mTipsDialog = NameCertificationUtils.getValidationCertification(this, mTipsDialog, bean.getMessage(), type);
            mTipsDialog.show();
        } else {
            if (type == NameCertificationUtils.CheckListener.Type.ADD_ORDER) {
                AddOrderActivity.startActivity(this);
            } else {
                WaybillScannerActivity.startActivity(this, WaybillScannerActivity.Type.SCAN_ADD_ORDER);
            }
        }
    }

    @Override
    public void onCanScanCodeAddOrder(String customerCode, ScanCodeOrderAddress addressData) {
        ScanCodeAddOrderActivity.startActivity(this, customerCode, addressData);
        finish();
    }

    @Override
    public void onCanNotScanCodeAddOrder() {
        onError("你没有权限扫码下单");
    }
}
